package utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 * RabbitMQUtils
 *
 * @author 丛有志
 * @date 2020/11/18 11:20
 * <p>
 * 版本        修改时间        作者        修改内容
 * V1.0        2020/11/18     丛有志        初始版本
 */
public class RabbitMQUtils {

    // 创建连接工厂
    private static ConnectionFactory connectionFactory;
        static {
            connectionFactory = new ConnectionFactory();
        // 设置连接rabbitmq主机
        connectionFactory.setHost("localhost");
        // 设置端口
        connectionFactory.setPort(5672);
        // 设置用户名
        connectionFactory.setUsername("ems");
        // 设置密码
        connectionFactory.setPassword("ems");
        // 设置虚拟机
        connectionFactory.setVirtualHost("/ems");
    }

    public static Connection getConnection() {
        try {
            // 获取连接对象
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void closeConnectionAndChanel(Channel channel, Connection connection) {
        try {
            if (null != channel) {
                channel.close();
            }
            if (null != connection) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

